$(function() {
	//显示菜单信息
	var head = $("#breadcrumbs");
	head.html('<ul class="breadcrumb">' +
		'<li><i class="icon-home"></i> <a href="/">首页</a><span class="divider"><i class="icon-angle-right"></i></span></li>' +
		'<li><a href="#">人事信息管理</a> <span class="divider"><i class="icon-angle-right"></i></span></li>' +
		'<li><a href="/staff">员工信息管理</a> <span class="divider"><i class="icon-angle-right"></i></span></li>' +
		'<li class="active">添加员工</li></ul>');
	var initialize = function() {
		var uid = $('#userId').val();
		$.ajax({
			url: '/api/getResource?',
			type: 'get',
			data: {'uid':uid, '_t':new Date().getTime()},
			success: function(data) {
				// console.info('datadata', data);
				var flag = false;
				for (var i = 0; i < data.length; i++) {
					if (data[i].resUrl == '/api/files' && data[i].operation == 'post') {
						flag = true;
					}
				}
				if (!flag) {
					$('#attach').css('display', 'none');
				}
			},
			error: function(data) {
				alert('error');
			}
		});

		$('.date-picker').datepicker({
			todayBtn: true,
			autoclose: true
		});

		$.ajax({
			url: '/api/region/provinces',
			type: 'Get',
			success: function(data) {
				$('#province').html('');
				for (var i = 0; i < data.length; i++) {
					var model = '<option value=' + data[i].id + '>' + data[i].name + '</option>';
					$('#province').append(model);
				}
			}
		});

		$('#province').change(function() {
			var proId = document.getElementById('province').value;
			$.ajax({
				url: '/api/region/citiy/' + proId,
				type: 'GET',
				success: function(data) {
					$('#registeredResidence').html('');
					for (var i = 0; i < data.length; i++) {
						var model = '<option value=' + data[i].name + '>' + data[i].name + '</option>';
						$('#registeredResidence').append(model);
					}
				}
			});
		});
		$.ajax({
			url: '/api/item/search?',
			type: 'GET',
			data: {'_t': new Date().getTime()},
			success: function(data) {
				for (var i = 0; i < data.length; i++) {
					if (data[i].type == '职位') {
						$('#position').append("<option value='" + data[i].showValue + "'>" + data[i].showValue + "</option>");
					}
					if (data[i].type == '职位类别') {
						$('#jobCategory').append("<option value='" + data[i].showValue + "'>" + data[i].showValue + "</option>");
					}
					if (data[i].type == '试用周期') {
						$('#probationaryPeriod').append("<option value='" + data[i].showValue + "'>" + data[i].showValue + "</option>");
					}
					if (data[i].type == '薪资档级') {
						$('#salaryLevel').append("<option value='" + data[i].showValue + "'>" + data[i].showValue + "</option>");
					}
					if (data[i].type == 'BAND级') {
						$('#bandLevel').append("<option value='" + data[i].showValue + "'>" + data[i].showValue + "</option>");
					}
					if (data[i].type == '工作地点') {
						$('#workPlace').append("<option value='" + data[i].showValue + "'>" + data[i].showValue + "</option>");
					}
				}
			}
		});
	};

	var getToday = function() {
		var http = new XMLHttpRequest;
		http.open("HEAD", ".", false);
		http.send(null);
		var today = new Date(http.getResponseHeader("Date"));
		var mounth = (today.getMonth() + 1) < 10 ? "0" + (today.getMonth() + 1) : (today.getMonth() + 1);
		var day = today.getDate() < 10 ? "0" + today.getDate() : today.getDate();
		var todayFormat = today.getFullYear() + "-" + mounth + "-" + day;
		return todayFormat;
	};

	initialize();

	//取消选择部门
	$("#cancle").click(function() {
		$("#showOrgs").modal('hide');
	});

	//选择部门
	$("#chooseDept").click(function() {
		$("#showOrgs").modal("show");
		$("#chooseOrg").ligerTree({
			url: '/api/organizations/getOrgTree?_t=' + new Date().getTime(),
			method: 'get',
			checkbox: false,
			nodeWidth: 120,
			idFieldName: "id",
			parentIDFieldName: 'pid',
			slide: false,
			onSelect: function(node) {
				actionNodeID = node.data.id;
				$.ajax({
					url: '/api/organizations/getParents/' + actionNodeID,
					type: 'get',
					success: function(result) {
						// console.info(result);
						// console.info(result[0]);
						var parentString = "";
						for (var i = result.length - 1; i >= 0; i--) {
							if (i != 0) {
								if (result[i].orgName == "分公司") {
									continue;
								} else {
									parentString += result[i].orgName + "/";
								}
							} else {
								parentString += result[i].orgName;
							}
						}

						if (result[0].orgType == "C") {
							alert("请选择部门");
						} else {
							$("#department").val(parentString);
							$("#deptId").val(result[0].id);
							$("#showOrgs").modal('hide');
						}
					}
				});
			}
		});
	});
	$("#noProbation").click(function() {
		$("#probationaryPeriod").val("0");
		$("#probationaryPeriod").attr("disabled", "true");
	});
	$("#yesProbation").click(function() {
		$("#probationaryPeriod").removeAttr("disabled");
	});

	//点击是否有试用期按钮，选中“是”，试用周期不可更改
	var ifProbations = document.getElementsByName("probation-radio");
	for (var i = 0; i < 2; i++) {
		if (ifProbations[i].checked) {
			var value = ifProbations[i].value;
			if (value == '0') {
				$('#probationaryPeriod').attr("disabled");
			}
		}
	}  //弹出底部提示框
	var showAlert = function(message, type, delay, callback) {
		$.globalMessenger().post({
			message: message,
			hideAfter: delay,
			type: type,
		});

		if (callback) {
			callback();
		}
	}

	var doActionAfterSecond = function(func, delay) {
		var t = setTimeout(function() {
			func();
			clearTimeout(t);
		}, delay * 1000);
	}

	var uploadFilesInfo = new Array();
	//上传控件代码
	$('#file_upload').uploadifive({
		'uploadScript': '/api/files',
		'buttonClass': 'btn upload-btn',
		'buttonText': '添加附件',
		'auto': true,
		'fileSizeLimit': (1024 * 5),
		'onUploadComplete': function(file, data) {
			if (data == 'noPrivilege') {
				bootbox.alert('您没有权限,操作失败！');
				return;
			}
			data = JSON.parse(data);
			//console.info('data2:',data);
			uploadFilesInfo.push(data);

		},
		'onCancel': function(file) {
			for (var i = 0; i < uploadFilesInfo.length; i++) {
				if (file.name == uploadFilesInfo[i].name) {
					uploadFilesInfo.splice(i, i + 1);
				}
			}
		}
	});

	$('#saveBtn').click(function() {
		var dataModel = buildDataModel();
		// console.info("state=", $('#empState option:selected').val());
		// return;
		if (dataModel.name == null || dataModel.name == '') {
			bootbox.alert("请填写姓名！");
			return;
		}
		if (dataModel.idNumber == null || dataModel.idNumber == '') {
			bootbox.alert("请填写身份证号！");
			return;
		}
		if (dataModel.email == null || dataModel.email == '') {
			bootbox.alert("请填写邮箱！");
			return;
		}
		if (dataModel.phone == null || dataModel.phone == '') {
			bootbox.alert("请填写联系电话！");
			return;
		}
		if (dataModel.jobNumber == null || dataModel.jobNumber == '') {
			bootbox.alert("请填写工号！");
			return;
		}
		if (dataModel.job == null || dataModel.job == '') {
			bootbox.alert("请填写职位！");
			return;
		}
		if (dataModel.jobCategory == null || dataModel.jobCategory == '') {
			bootbox.alert("请选择职位类别！");
			return;
		}
		if (dataModel.departmentId == null || dataModel.departmentId == '') {
			bootbox.alert("请选择部门！");
			return;
		}
		if (dataModel.state == null || dataModel.state == '') {
			bootbox.alert("请选择状态！");
			return;
		}

		if (dataModel.ifProbation == "1" && (dataModel.probationaryPeriod == null || dataModel.probationaryPeriod == '')) {
			bootbox.alert("请选择试用周期！");
			return;
		}
		//检查姓名、工号的存在性
		var name = dataModel.name;
		var jobNumber = dataModel.jobNumber;

		$.ajax({
			url: '/api/employee/all?',
			type: 'GET',
			data: {'_t': new Date().getTime()},
			success: function(data) {
				for (var i = 0; i < data.length; i++) {
					if (data[i].jobNumber == jobNumber) {
						bootbox.alert('工号已存在！');
						return;
					}
				}
				addEmployee(dataModel);
			},
			error: function() {
				showAlert("添加失败", "error", 2);
			}
		});


	});

	var addEmployee = function(data) {
		$.ajax({
			url: '/api/employee',
			type: 'POST',
			data: data,
			success: function(result) {
				if (result == 'noPrivilege') {
					bootbox.alert('您没有权限,操作失败');
					return;
				}
				bootbox.alert('添加成功！', function() {
					window.location.href = "/staff?hisPage=-1";
				});
			},
			error: function(result) {
				showAlert("添加失败", "error", 2);
			}
		});
	};

	var buildDataModel = function() {
		var $name = $('#name').val(), //姓名
			$idNumber = $('#idNumber').val(), //身份证号
			$address = $('#address').val(), //通讯地址
			$phoneNum = $('#phoneNum').val(), //联系电话
			$eduBackground = $('#eduBackground option:selected').val(), //学历
			$registeredResidence = $('#registeredResidence option:selected').val(), //户口所在地
			$workPlace = $('#workPlace option:selected').val(), //工作地点
			$emContactPersonAndTele = $('#emContactPersonAndTele').val(), ///紧急联系人
			$graduInstitutions = $('#graduInstitutions').val(), //毕业院校
			$birthDate = $('#birthDate').val(), //出生日期
			$nodeType = $('#nodeType option:selected').val(), //户口类型
			$email = $('#email').val(), //个人邮箱
			$emContactPersonAndTelePhone = $('#emContactPersonAndTelePhone').val(), //紧急联系人电话
			$graduateTime = $('#graduateTime').val(), //毕业时间
			$position = $('#position option:selected').val(), //职位
			$jobCategory = $('#jobCategory option:selected').val(), //职位类别
			$entryTime = $('#entryTime').val(), //入职时间
			$deptId = document.getElementById('deptId').value, //部门
			$departureTime = $('#departureTime').val(), //离职时间
			$jobNumber = $('#jobNumber').val(), //工号
			//==========合同保密协议?????
			$dateOfCStart = $('#dateOfCStart').val(), //合同开始时间
			// $dateOfRenewalStart = $('#dateOfRenewalStart').val(), //合同续签开始时间
			$bandLevel = $('#bandLevel option:selected').val(), //BAND级
			$currentSalary = $('#currentSalary').val(), //当前月薪
			$bankCardNum = $('#bankCardNum').val(), //银行卡号
			$contractNum = $('#contractNum').val(), //合同编号
			//==========竞业协议?????
			$dateOfCEnd = $('#dateOfCEnd').val(), //合同结束时间
			// $dateOfRenewalEnd = $('#dateOfRenewalEnd').val(), //合同续签结束时间
			// $lastDateOfPromotion = $('#lastDateOfPromotion').val(), //最后一次晋级时间
			$salaryLevel = $('#salaryLevel option:selected').val(), //薪资档级
			$smInsuranceCard = $('#smInsuranceCard').val(), //社保医保卡号
			//==========劳动合同主体?????
			$probationaryPeriod = $('#probationaryPeriod option:selected').val(), //试用周期
			$confirmationDate = $('#confirmationDate').val(), //转正日期
			$lastDateOfExamination = $('#lastDateOfExamination').val(), //最后一次体检日期
			// $lastDateOfRise = $('#lastDateOfExamination').val(), //最后一次加薪日期
			$housingFundCard = $('#housingFundCard').val(), //住房公积金卡号
		// $state = $('#state').val(); //在职状态
		    $state = $('#empState option:selected').val();//员工状态

		var $gender; //性别
		var $ifProbation; //是否有试用期
		var genders = document.getElementsByName("gender-radio");
		var ifProbations = document.getElementsByName("probation-radio");

		for (var i = 0; i < 2; i++) {
			if (genders[i].checked) {
				// alert(genders[i].value);
				$gender = genders[i].value;
			}
			if (ifProbations[i].checked) {
				// alert(ifProbations[i].value);
				$ifProbation = ifProbations[i].value;
			}
		}

		var model = {};
		model.name = $name;
		model.gender = $gender;
		model.idNumber = $idNumber;
		model.address = $address;
		model.email = $email;

		model.phone = $phoneNum;
		model.education = $eduBackground;
		model.registeredResidence = $registeredResidence;
		model.workPlace = $workPlace;
		model.emContactPerson = $emContactPersonAndTele;

		model.emContactPhone = $emContactPersonAndTelePhone;
		model.graduInstitutions = $graduInstitutions;
		model.birthDate = $birthDate;
		model.residenceType = $nodeType;
		model.graduateTime = $graduateTime;

		model.jobNumber = $jobNumber;
		model.contractNum = $contractNum;
		model.job = $position;
		model.jobCategory = $jobCategory;
		model.departmentId = $deptId;

		model.state = $state;
		model.entryTime = $entryTime;
		model.departureTime = $departureTime;
		model.dateOfCStart = $dateOfCStart;
		model.dateOfCEnd = $dateOfCEnd;

		// model.dateOfRenewalStart = $dateOfRenewalStart;
		// model.dateOfRenewalEnd = $dateOfRenewalEnd;
		model.bandLevel = $bandLevel;
		model.currentSalary = $currentSalary * 1;
		model.salaryLevel = $salaryLevel;

		model.bankCardNum = $bankCardNum;
		model.housingFundCard = $housingFundCard;
		model.smInsuranceCard = $smInsuranceCard;
		model.ifProbation = $ifProbation;
		model.probationaryPeriod = $probationaryPeriod;

		model.confirmationDate = $confirmationDate;
		// model.lastDateOfPromotion = $lastDateOfPromotion;
		model.lastDateOfExamination = $lastDateOfExamination;
		// model.lastDateOfRise = $lastDateOfRise;
		model.file = uploadFilesInfo;
		return model;
	};

});